<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    6-日志和调试工具栏.md |  
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-django/6-日志和调试工具栏"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  6-日志和调试工具栏.md
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/11/11/django/6-%E6%97%A5%E5%BF%97%E5%92%8C%E8%B0%83%E8%AF%95%E5%B7%A5%E5%85%B7%E6%A0%8F/" class="article-date">
  <time datetime="2020-11-10T16:00:00.000Z" itemprop="datePublished">2020-11-11</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/django/">django</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.8k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">11 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h2 id="日志和调试工具栏"><a href="#日志和调试工具栏" class="headerlink" title="日志和调试工具栏"></a>日志和调试工具栏</h2><h3 id="配置日志"><a href="#配置日志" class="headerlink" title="配置日志"></a>配置日志</h3><p>项目开发阶段，显示足够的调试信息以辅助开发人员调试代码还是非常必要的；项目上线以后，将系统运行时出现的警告、错误等信息记录下来以备相关人员了解系统运行状况并维护代码也是很有必要的。与此同时，采集日志数据也是为网站做数字化运营奠定一个基础，通过对系统运行日志的分析，我们可以监测网站的流量以及流量分布，同时还可以挖掘出用户的使用习惯和行为模式。</p>
<p>接下来，我们先看看如何通过Django的配置文件来配置日志。Django的日志配置基本可以参照官方文档再结合项目实际需求来进行，这些内容基本上可以从官方文档上复制下来，然后进行局部的调整即可，下面给出一些参考配置。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line">LOGGING = &#123;</span><br><span class="line">    <span class="string">&#x27;version&#x27;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="comment"># 是否禁用已经存在的日志器</span></span><br><span class="line">    <span class="string">&#x27;disable_existing_loggers&#x27;</span>: <span class="literal">False</span>,</span><br><span class="line">    <span class="comment"># 日志格式化器</span></span><br><span class="line">    <span class="string">&#x27;formatters&#x27;</span>: &#123;</span><br><span class="line">        <span class="string">&#x27;simple&#x27;</span>: &#123;</span><br><span class="line">            <span class="string">&#x27;format&#x27;</span>: <span class="string">&#x27;%(asctime)s %(module)s.%(funcName)s: %(message)s&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;datefmt&#x27;</span>: <span class="string">&#x27;%Y-%m-%d %H:%M:%S&#x27;</span>,</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">&#x27;verbose&#x27;</span>: &#123;</span><br><span class="line">            <span class="string">&#x27;format&#x27;</span>: <span class="string">&#x27;%(asctime)s %(levelname)s [%(process)d-%(threadName)s] &#x27;</span></span><br><span class="line">                      <span class="string">&#x27;%(module)s.%(funcName)s line %(lineno)d: %(message)s&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;datefmt&#x27;</span>: <span class="string">&#x27;%Y-%m-%d %H:%M:%S&#x27;</span>,</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment"># 日志过滤器</span></span><br><span class="line">    <span class="string">&#x27;filters&#x27;</span>: &#123;</span><br><span class="line">        <span class="comment"># 只有在Django配置文件中DEBUG值为True时才起作用</span></span><br><span class="line">        <span class="string">&#x27;require_debug_true&#x27;</span>: &#123;</span><br><span class="line">            <span class="string">&#x27;()&#x27;</span>: <span class="string">&#x27;django.utils.log.RequireDebugTrue&#x27;</span>,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment"># 日志处理器</span></span><br><span class="line">    <span class="string">&#x27;handlers&#x27;</span>: &#123;</span><br><span class="line">        <span class="comment"># 输出到控制台</span></span><br><span class="line">        <span class="string">&#x27;console&#x27;</span>: &#123;</span><br><span class="line">            <span class="string">&#x27;class&#x27;</span>: <span class="string">&#x27;logging.StreamHandler&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;level&#x27;</span>: <span class="string">&#x27;DEBUG&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;filters&#x27;</span>: [<span class="string">&#x27;require_debug_true&#x27;</span>],</span><br><span class="line">            <span class="string">&#x27;formatter&#x27;</span>: <span class="string">&#x27;simple&#x27;</span>,</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment"># 输出到文件(每周切割一次)</span></span><br><span class="line">        <span class="string">&#x27;file1&#x27;</span>: &#123;</span><br><span class="line">            <span class="string">&#x27;class&#x27;</span>: <span class="string">&#x27;logging.handlers.TimedRotatingFileHandler&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;filename&#x27;</span>: <span class="string">&#x27;access.log&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;when&#x27;</span>: <span class="string">&#x27;W0&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;backupCount&#x27;</span>: <span class="number">12</span>,</span><br><span class="line">            <span class="string">&#x27;formatter&#x27;</span>: <span class="string">&#x27;simple&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;level&#x27;</span>: <span class="string">&#x27;INFO&#x27;</span>,</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment"># 输出到文件(每天切割一次)</span></span><br><span class="line">        <span class="string">&#x27;file2&#x27;</span>: &#123;</span><br><span class="line">            <span class="string">&#x27;class&#x27;</span>: <span class="string">&#x27;logging.handlers.TimedRotatingFileHandler&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;filename&#x27;</span>: <span class="string">&#x27;error.log&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;when&#x27;</span>: <span class="string">&#x27;D&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;backupCount&#x27;</span>: <span class="number">31</span>,</span><br><span class="line">            <span class="string">&#x27;formatter&#x27;</span>: <span class="string">&#x27;verbose&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;level&#x27;</span>: <span class="string">&#x27;WARNING&#x27;</span>,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment"># 日志器记录器</span></span><br><span class="line">    <span class="string">&#x27;loggers&#x27;</span>: &#123;</span><br><span class="line">        <span class="string">&#x27;django&#x27;</span>: &#123;</span><br><span class="line">            <span class="comment"># 需要使用的日志处理器</span></span><br><span class="line">            <span class="string">&#x27;handlers&#x27;</span>: [<span class="string">&#x27;console&#x27;</span>, <span class="string">&#x27;file1&#x27;</span>, <span class="string">&#x27;file2&#x27;</span>],</span><br><span class="line">            <span class="comment"># 是否向上传播日志信息</span></span><br><span class="line">            <span class="string">&#x27;propagate&#x27;</span>: <span class="literal">True</span>,</span><br><span class="line">            <span class="comment"># 日志级别(不一定是最终的日志级别)</span></span><br><span class="line">            <span class="string">&#x27;level&#x27;</span>: <span class="string">&#x27;DEBUG&#x27;</span>,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>大家可能已经注意到了，上面日志配置中的<code>formatters</code>是<strong>日志格式化器</strong>，它代表了如何格式化输出日志，其中格式占位符分别表示：</p>
<ol>
<li><code>%(name)s</code> - 记录器的名称</li>
<li><code>%(levelno)s</code> - 数字形式的日志记录级别</li>
<li><code>%(levelname)s</code> - 日志记录级别的文本名称</li>
<li><code>%(filename)s</code> - 执行日志记录调用的源文件的文件名称</li>
<li><code>%(pathname)s</code> - 执行日志记录调用的源文件的路径名称</li>
<li><code>%(funcName)s</code> - 执行日志记录调用的函数名称</li>
<li><code>%(module)s</code> - 执行日志记录调用的模块名称</li>
<li><code>%(lineno)s</code> - 执行日志记录调用的行号</li>
<li><code>%(created)s</code> - 执行日志记录的时间</li>
<li><code>%(asctime)s</code> - 日期和时间</li>
<li><code>%(msecs)s</code> - 毫秒部分</li>
<li><code>%(thread)d</code> - 线程ID（整数）</li>
<li><code>%(threadName)s</code> - 线程名称</li>
<li><code>%(process)d</code> - 进程ID （整数）</li>
</ol>
<p>日志配置中的handlers用来指定<strong>日志处理器</strong>，简单的说就是指定将日志输出到控制台还是文件又或者是网络上的服务器，可用的处理器包括：</p>
<ol>
<li><code>logging.StreamHandler(stream=None)</code> - 可以向类似与<code>sys.stdout</code>或者<code>sys.stderr</code>的任何文件对象输出信息</li>
<li><code>logging.FileHandler(filename, mode=&#39;a&#39;, encoding=None, delay=False)</code> - 将日志消息写入文件</li>
<li><code>logging.handlers.DatagramHandler(host, port)</code> - 使用UDP协议，将日志信息发送到指定主机和端口的网络主机上</li>
<li><code>logging.handlers.HTTPHandler(host, url)</code> - 使用HTTP的GET或POST方法将日志消息上传到一台HTTP 服务器</li>
<li><code>logging.handlers.RotatingFileHandler(filename, mode=&#39;a&#39;, maxBytes=0, backupCount=0, encoding=None, delay=False)</code> - 将日志消息写入文件，如果文件的大小超出<code>maxBytes</code>指定的值，那么将重新生成一个文件来记录日志</li>
<li><code>logging.handlers.SocketHandler(host, port)</code> - 使用TCP协议，将日志信息发送到指定主机和端口的网络主机上 </li>
<li><code>logging.handlers.SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0)</code> - 将日志输出到指定的邮件地址</li>
<li><code>logging.MemoryHandler(capacity, flushLevel=ERROR, target=None, flushOnClose=True)</code> - 将日志输出到内存指定的缓冲区中</li>
</ol>
<p>上面每个日志处理器都指定了一个名为<code>level</code>的属性，它代表了日志的级别，不同的日志级别反映出日志中记录信息的严重性。Python中定义了六个级别的日志，按照从低到高的顺序依次是：NOTSET、DEBUG、INFO、WARNING、ERROR、CRITICAL。</p>
<p>最后配置的<strong>日志记录器</strong>是用来真正输出日志的，Django框架提供了如下所示的内置记录器：</p>
<ol>
<li><code>django</code> - 在Django层次结构中的所有消息记录器</li>
<li><code>django.request</code> - 与请求处理相关的日志消息。5xx响应被视为错误消息；4xx响应被视为为警告消息</li>
<li><code>django.server</code> - 与通过runserver调用的服务器所接收的请求相关的日志消息。5xx响应被视为错误消息；4xx响应被记录为警告消息；其他一切都被记录为INFO</li>
<li><code>django.template</code> - 与模板渲染相关的日志消息</li>
<li><code>django.db.backends</code> - 有与数据库交互产生的日志消息，如果希望显示ORM框架执行的SQL语句，就可以使用该日志记录器。</li>
</ol>
<p>日志记录器中配置的日志级别有可能不是最终的日志级别，因为还要参考日志处理器中配置的日志级别，取二者中级别较高者作为最终的日志级别。</p>
<h3 id="配置Django-Debug-Toolbar"><a href="#配置Django-Debug-Toolbar" class="headerlink" title="配置Django-Debug-Toolbar"></a>配置Django-Debug-Toolbar</h3><p>如果想调试你的Django项目，你一定不能不过名为Django-Debug-Toolbar的神器，它是项目开发阶段辅助调试和优化的必备工具，只要配置了它，就可以很方便的查看到如下表所示的项目运行信息，这些信息对调试项目和优化Web应用性能都是至关重要的。</p>
<table>
<thead>
<tr>
<th>项目</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>Versions</td>
<td>Django的版本</td>
</tr>
<tr>
<td>Time</td>
<td>显示视图耗费的时间</td>
</tr>
<tr>
<td>Settings</td>
<td>配置文件中设置的值</td>
</tr>
<tr>
<td>Headers</td>
<td>HTTP请求头和响应头的信息</td>
</tr>
<tr>
<td>Request</td>
<td>和请求相关的各种变量及其信息</td>
</tr>
<tr>
<td>StaticFiles</td>
<td>静态文件加载情况</td>
</tr>
<tr>
<td>Templates</td>
<td>模板的相关信息</td>
</tr>
<tr>
<td>Cache</td>
<td>缓存的使用情况</td>
</tr>
<tr>
<td>Signals</td>
<td>Django内置的信号信息</td>
</tr>
<tr>
<td>Logging</td>
<td>被记录的日志信息</td>
</tr>
<tr>
<td>SQL</td>
<td>向数据库发送的SQL语句及其执行时间</td>
</tr>
</tbody></table>
<ol>
<li><p>安装Django-Debug-Toolbar。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install django-debug-toolbar</span><br></pre></td></tr></table></figure>
</li>
<li><p>配置 - 修改settings.py。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">INSTALLED_APPS = [</span><br><span class="line">    <span class="string">&#x27;debug_toolbar&#x27;</span>,</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">MIDDLEWARE = [</span><br><span class="line">    <span class="string">&#x27;debug_toolbar.middleware.DebugToolbarMiddleware&#x27;</span>,</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">DEBUG_TOOLBAR_CONFIG = &#123;</span><br><span class="line">    <span class="comment"># 引入jQuery库</span></span><br><span class="line">    <span class="string">&#x27;JQUERY_URL&#x27;</span>: <span class="string">&#x27;https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js&#x27;</span>,</span><br><span class="line">    <span class="comment"># 工具栏是否折叠</span></span><br><span class="line">    <span class="string">&#x27;SHOW_COLLAPSED&#x27;</span>: <span class="literal">True</span>,</span><br><span class="line">    <span class="comment"># 是否显示工具栏</span></span><br><span class="line">    <span class="string">&#x27;SHOW_TOOLBAR_CALLBACK&#x27;</span>: <span class="keyword">lambda</span> x: <span class="literal">True</span>,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>配置 - 修改urls.py。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> settings.DEBUG:</span><br><span class="line"></span><br><span class="line">    <span class="keyword">import</span> debug_toolbar</span><br><span class="line"></span><br><span class="line">    urlpatterns.insert(<span class="number">0</span>, path(<span class="string">&#x27;__debug__/&#x27;</span>, include(debug_toolbar.urls)))</span><br></pre></td></tr></table></figure>
</li>
<li><p>在配置好Django-Debug-Toolbar之后，页面右侧会看到一个调试工具栏，如下图所示，上面包括了如前所述的各种调试信息，包括执行时间、项目设置、请求头、SQL、静态资源、模板、缓存、信号等，查看起来非常的方便。</p>
<p><img src="http://iubest.gitee.io/pic/debug-toolbar.png" alt="img"></p>
</li>
</ol>
<h3 id="优化ORM代码"><a href="#优化ORM代码" class="headerlink" title="优化ORM代码"></a>优化ORM代码</h3><p>在配置了日志或Django-Debug-Toolbar之后，我们可以查看一下之前将老师数据导出成Excel报表的视图函数执行情况，这里我们关注的是ORM框架生成的SQL查询到底是什么样子的，相信这里的结果会让你感到有一些意外。执行<code>Teacher.objects.all()</code>之后我们可以注意到，在控制台看到的或者通过Django-Debug-Toolbar输出的SQL是下面这样的：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="string">`tb_teacher`</span>.<span class="string">`no`</span>, <span class="string">`tb_teacher`</span>.<span class="string">`name`</span>, <span class="string">`tb_teacher`</span>.<span class="string">`detail`</span>, <span class="string">`tb_teacher`</span>.<span class="string">`photo`</span>, <span class="string">`tb_teacher`</span>.<span class="string">`good_count`</span>, <span class="string">`tb_teacher`</span>.<span class="string">`bad_count`</span>, <span class="string">`tb_teacher`</span>.<span class="string">`sno`</span> <span class="keyword">FROM</span> <span class="string">`tb_teacher`</span>; args=()</span><br><span class="line"><span class="keyword">SELECT</span> <span class="string">`tb_subject`</span>.<span class="string">`no`</span>, <span class="string">`tb_subject`</span>.<span class="string">`name`</span>, <span class="string">`tb_subject`</span>.<span class="string">`intro`</span>, <span class="string">`tb_subject`</span>.<span class="string">`create_date`</span>, <span class="string">`tb_subject`</span>.<span class="string">`is_hot`</span> <span class="keyword">FROM</span> <span class="string">`tb_subject`</span> <span class="keyword">WHERE</span> <span class="string">`tb_subject`</span>.<span class="string">`no`</span> = <span class="number">101</span>; args=(101,)</span><br><span class="line"><span class="keyword">SELECT</span> <span class="string">`tb_subject`</span>.<span class="string">`no`</span>, <span class="string">`tb_subject`</span>.<span class="string">`name`</span>, <span class="string">`tb_subject`</span>.<span class="string">`intro`</span>, <span class="string">`tb_subject`</span>.<span class="string">`create_date`</span>, <span class="string">`tb_subject`</span>.<span class="string">`is_hot`</span> <span class="keyword">FROM</span> <span class="string">`tb_subject`</span> <span class="keyword">WHERE</span> <span class="string">`tb_subject`</span>.<span class="string">`no`</span> = <span class="number">101</span>; args=(101,)</span><br><span class="line"><span class="keyword">SELECT</span> <span class="string">`tb_subject`</span>.<span class="string">`no`</span>, <span class="string">`tb_subject`</span>.<span class="string">`name`</span>, <span class="string">`tb_subject`</span>.<span class="string">`intro`</span>, <span class="string">`tb_subject`</span>.<span class="string">`create_date`</span>, <span class="string">`tb_subject`</span>.<span class="string">`is_hot`</span> <span class="keyword">FROM</span> <span class="string">`tb_subject`</span> <span class="keyword">WHERE</span> <span class="string">`tb_subject`</span>.<span class="string">`no`</span> = <span class="number">101</span>; args=(101,)</span><br><span class="line"><span class="keyword">SELECT</span> <span class="string">`tb_subject`</span>.<span class="string">`no`</span>, <span class="string">`tb_subject`</span>.<span class="string">`name`</span>, <span class="string">`tb_subject`</span>.<span class="string">`intro`</span>, <span class="string">`tb_subject`</span>.<span class="string">`create_date`</span>, <span class="string">`tb_subject`</span>.<span class="string">`is_hot`</span> <span class="keyword">FROM</span> <span class="string">`tb_subject`</span> <span class="keyword">WHERE</span> <span class="string">`tb_subject`</span>.<span class="string">`no`</span> = <span class="number">101</span>; args=(101,)</span><br><span class="line"><span class="keyword">SELECT</span> <span class="string">`tb_subject`</span>.<span class="string">`no`</span>, <span class="string">`tb_subject`</span>.<span class="string">`name`</span>, <span class="string">`tb_subject`</span>.<span class="string">`intro`</span>, <span class="string">`tb_subject`</span>.<span class="string">`create_date`</span>, <span class="string">`tb_subject`</span>.<span class="string">`is_hot`</span> <span class="keyword">FROM</span> <span class="string">`tb_subject`</span> <span class="keyword">WHERE</span> <span class="string">`tb_subject`</span>.<span class="string">`no`</span> = <span class="number">103</span>; args=(103,)</span><br><span class="line"><span class="keyword">SELECT</span> <span class="string">`tb_subject`</span>.<span class="string">`no`</span>, <span class="string">`tb_subject`</span>.<span class="string">`name`</span>, <span class="string">`tb_subject`</span>.<span class="string">`intro`</span>, <span class="string">`tb_subject`</span>.<span class="string">`create_date`</span>, <span class="string">`tb_subject`</span>.<span class="string">`is_hot`</span> <span class="keyword">FROM</span> <span class="string">`tb_subject`</span> <span class="keyword">WHERE</span> <span class="string">`tb_subject`</span>.<span class="string">`no`</span> = <span class="number">103</span>; args=(103,)</span><br></pre></td></tr></table></figure>

<p>这里的问题通常被称为“1+N查询”（有的地方也将其称之为“N+1查询”），原本获取老师的数据只需要一条SQL，但是由于老师关联了学科，当我们查询到<code>N</code>条老师的数据时，Django的ORM框架又向数据库发出了<code>N</code>条SQL去查询老师所属学科的信息。每条SQL执行都会有较大的开销而且会给数据库服务器带来压力，如果能够在一条SQL中完成老师和学科的查询肯定是更好的做法，这一点也很容易做到，相信大家已经想到怎么做了。是的，我们可以使用连接查询，但是在使用Django的ORM框架时如何做到这一点呢？对于多对一关联（如投票应用中的老师和学科），我们可以使用<code>QuerySet</code>的用<code>select_related()</code>方法来加载关联对象；而对于多对多关联（如电商网站中的订单和商品），我们可以使用<code>prefetch_related()</code>方法来加载关联对象。</p>
<p>在导出老师Excel报表的视图函数中，我们可以按照下面的方式优化代码。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">queryset = Teacher.objects.all().select_related(<span class="string">&#x27;subject&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p>事实上，用ECharts生成前端报表的视图函数中，查询老师好评和差评数据的操作也能够优化，因为在这个例子中，我们只需要获取老师的姓名、好评数和差评数这三项数据，但是在默认的情况生成的SQL会查询老师表的所有字段。可以用<code>QuerySet</code>的<code>only()</code>方法来指定需要查询的属性，也可以用<code>QuerySet</code>的<code>defer()</code>方法来指定暂时不需要查询的属性，这样生成的SQL会通过投影操作来指定需要查询的列，从而改善查询性能，代码如下所示：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">queryset = Teacher.objects.all().only(<span class="string">&#x27;name&#x27;</span>, <span class="string">&#x27;good_count&#x27;</span>, <span class="string">&#x27;bad_count&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p>当然，如果要统计出每个学科的老师好评和差评的平均数，利用Django的ORM框架也能够做到，代码如下所示：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">queryset = Teacher.objects.values(<span class="string">&#x27;subject&#x27;</span>).annotate(good=Avg(<span class="string">&#x27;good_count&#x27;</span>), bad=Avg(<span class="string">&#x27;bad_count&#x27;</span>))</span><br></pre></td></tr></table></figure>

<p>这里获得的<code>QuerySet</code>中的元素是字典对象，每个字典中有三组键值对，分别是代表学科编号的<code>subject</code>、代表好评数的<code>good</code>和代表差评数的<code>bad</code>。如果想要获得学科的名称而不是编号，可以按照如下所示的方式调整代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">queryset = Teacher.objects.values(<span class="string">&#x27;subject__name&#x27;</span>).annotate(good=Avg(<span class="string">&#x27;good_count&#x27;</span>), bad=Avg(<span class="string">&#x27;bad_count&#x27;</span>))</span><br></pre></td></tr></table></figure>

<p>可见，Django的ORM框架允许我们用面向对象的方式完成关系数据库中的分组和聚合查询。</p>
<p>见，Django的ORM框架允许我们用面向对象的方式完成关系数据库中的分组和聚合查询。</p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2020/11/11/django/6-%E6%97%A5%E5%BF%97%E5%92%8C%E8%B0%83%E8%AF%95%E5%B7%A5%E5%85%B7%E6%A0%8F/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/django/" rel="tag">django</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/11/11/django/5-%E5%88%B6%E4%BD%9C%E6%8A%A5%E8%A1%A8/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            5-制作报表.md
          
        </div>
      </a>
    
    
      <a href="/2020/11/11/django/7-%E4%B8%AD%E9%97%B4%E4%BB%B6%E7%9A%84%E5%BA%94%E7%94%A8/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">7-中间件的应用.md</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> TzWind
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        由 <a href="https://hexo.io" target="_blank">Hexo</a> 强力驱动
        <span class="division">|</span>
        主题 - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Hexo"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" target="_blank" rel="noopener" href="http://www.baidu.com">百度</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2019/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>